import { Button, DatePicker, RangePicker, Space } from 'ant-design-vue'
import type VXETable from 'vxe-table'

import { TABLE_RENDERER } from '@/constants'

/** 渲染器注册 */
export function useTableRenderer(vxe: typeof VXETable) {
  vxe.renderer.add(TABLE_RENDERER.FormItemBtns, {
    renderItemContent(renderOpts, params) {
      return [
        <Space>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button htmlType="reset">重置</Button>
        </Space>
      ]
    }
  })

  vxe.renderer.add(TABLE_RENDERER.FormItemDate, {
    renderItemContent(renderOpts, params) {
      const { props } = renderOpts
      const { data, property } = params

      if (!props) {
        throw 'FormItemDate 必须设置 props'
      }

      let Component: any

      if (!props.type) {
        throw 'FormItemDate 必须设置 type'
      }

      if (props.type === 'range' && !props.keys) {
        throw 'FormItemDate 必须设置 keys'
      }

      switch (props!.type) {
        case 'date':
          Component = DatePicker
          break
        case 'range':
          Component = RangePicker
          break
        default:
          break
      }

      function handleChange(value) {
        const keys = props!.keys

        if (keys) {
          const [begin, end] = keys
          const [startVal, endVal] = value

          data[begin] = startVal
          data[end] = endVal
        }
      }

      return [
        <Component
          v-model:value={data[property]}
          onChange={handleChange}
          {...props}
        />
      ]
    },
    itemResetMethod(params) {
      const { data, item, field } = params
      const keys = item.itemRender.props!.keys

      if (keys) {
        const [begin, end] = keys

        data[begin] = null
        data[end] = null
        data[field] = null
      }
    }
  })
}
